var express=require('express');
var bodyParser = require('body-parser');
var path = require('path');
var favicon = require('serve-favicon');
var formidable=require('formidable');
var expressSession=require('express-session');
var cookieParser=require('cookie-parser');
var logger=require('morgan');
var plogger=require('express-logger');
var nodemailer=require('nodemailer');

var app=express();
app.set('port',process.env.PORT||3000);

// switch (app.get('env')) {
//   case 'development':
//     //紧凑的彩色日志
//     app.use(logger('dev'));
//     break;
//   default:
//     //使用express-logger 记录日志文件
//     app.use(plogger({
//       path:__dirname+'/log/requests.log',
//     }));
//
//
// }

// var mailTransport=nodemailer.createTransport('SMTP',{
//   host:'smtp.163.com',
//   secureConnecton:true,
//   auth:{
//     user:'xxxUser',
//     pass:'xxxPass'
//   }
// });
//设置handlebars视图引擎

var exphbs=require('express-handlebars');

app.engine('html',exphbs({
  layoutsDir:'views',
  defaultLayout:'layout',
  extname:'.html'
}));
app.set('view engine','html');

app.use(express.static(__dirname + '/public'));
// app.use(logger('dev'));
//
// //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: false }));
// app.use(cookieParser);
// app.use(expressSession);



app.use(function(req,res,next){
  res.locals.showTests=app.get('env')!='production' && req.query.test==='1';
  next();
});

// app.use(function(req,res,next){
//   res.locals.flash=req.session.flash;
//   delete req.session.flash;
//   next();
// });


// app.use(function(req,res,next){
// var cluster = require('cluster');
// if(cluster.isWorker) console.log('Worker %d received request',
// cluster.worker.id);
// });

app.get('/',function(req,res){
   res.render('index');
});

app.post('/upload-test', function(req, res) {
  var form=new formidable.IncomingForm();
  form.parse(req,function(err,fields,files){

    if(err){
      return res.redirect(303,'/error');

    }
    console.log('received fields:');
    console.log(fields);
    console.log('received files');
    console.log(files);
    res.redirect(303,'/thank-you');
  });
});

app.get('/error', function(req, res) {
  res.render('error');
});

app.get('/thank-you', function(req, res) {
  res.render('thank-you');
});

var fortune=require('./lib/fortune.js');

app.get('/about',function(req,res){

   res.render('about',{
     fortune:fortune.getFortune(),
    pageTestScript:'/qa/tests-about.js'
  });
});


app.get('/headers',function(req,res){
  res.set('Content-Type','text/plain');
  var s='';
  for(var name in req.headers){
    s+=name+':'+req.headers[name]+'\n';
  }
  res.send(s);
});

var Attraction=require('./models/attraction.js');
app.get('/api/attrations',  function(req, res) {
  Attraction.fin({approved:true},function(err,attrations){
    if(err) return res.send(500,'Error occurred:database error.');
    res.json(attractions.map(function(a){
      return {
        name:a.name,
        id:a._id,
        description:a.description,
        location:a.location,
      }
    }));
  });
});


//定制404错误
app.use(function (req,res) {

  res.status(404);
  res.render('404');
});
//定制500错误
app.use(function(err,req,res,next){
  console.error(err.stack);

  res.status(500);
  res.render('500');
});



function startServer(){
  app.listen(app.get('port'),function(){

    console.log('Express started on http://localhost:'+
    app.get('port')+'; press Ctrl-C to terminate.');
  });

}

if (require.main===module){
  //如果是node 命令运行meadowlark.js 则执行:

  startServer()
}else{
  //将startServer方法导出
  module.exports=startServer;
}
